package com.luculent.action;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.luculent.base.section.WJWSend;
import com.luculent.result.Response;
import com.luculent.utils.EncryptUtils;
import com.luculent.utils.WJWTableUtils;

import lombok.extern.slf4j.Slf4j;  

@Controller 
@RequestMapping("/cf_wjwmenggulangkunweijiwei")
@Slf4j
public class WJWController extends WJWSend{
	
	private static String agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36";
	private String pageSize = "100";
	
	@RequestMapping(params ="iw-cmd=code") 
    public void code(HttpServletResponse response) throws UnsupportedOperationException, IOException{
		HttpClient client =  getClientSSL();
		HttpGet siginPost = new HttpGet("http://localhost/framework/util/image.jsp?r="+Math.random()); 
		siginPost.setHeader("User-Agent", agent);
		siginPost.setHeader("Host","localhost"); 
		HttpResponse HtmlResp  = client.execute(siginPost);
		String cookies = showCookies(HtmlResp.getAllHeaders());
		super.cookie = cookies; 
		response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Content-Type","image/jpeg;charset=UTF-8");//设置响应的媒体类型，这样浏览器会识别出响应的是图片
		BufferedImage buffImg = ImageIO.read(HtmlResp.getEntity().getContent());
		ServletOutputStream sos = response.getOutputStream();
        ImageIO.write(buffImg, "jpeg", sos);
        sos.close(); 
//		response.getOutputStream().write(IOUtils.toByteArray(HtmlResp.getEntity().getContent()));
//		response.flushBuffer(); 
    } 
	
	@RequestMapping(params ="iw-cmd=login") 
	@ResponseBody
    public String login(@RequestParam(value="username",required = true) String username,
    		@RequestParam(value="password",required = true) String password,
    		@RequestParam(value="code",required = true) String code) throws UnsupportedOperationException, IOException{
		Response response = new Response();
		response.head.rtnCode = "000000"; 
		HttpClient client =  getClientSSL(); 
		HttpPost siginPost = new HttpPost("https://localhost/login/login.do"); 
		siginPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36");
		siginPost.setHeader("Host","localhost"); 
		siginPost.setHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8"); 
		siginPost.setHeader("X-Requested-With","XMLHttpRequest");  
		siginPost.setHeader("Cookie",super.cookie);  
		List <NameValuePair> nvps = new ArrayList <NameValuePair>();
		nvps.add(new BasicNameValuePair("username",username));
		nvps.add(new BasicNameValuePair("password",password = EncryptUtils.mD5(username+EncryptUtils.mD5(password))));
		nvps.add(new BasicNameValuePair("width","2018"));
		nvps.add(new BasicNameValuePair("codevalue",code));
		//转码  封装成请求实体
		HttpEntity reqEntity = new UrlEncodedFormEntity(nvps,Consts.UTF_8); 
		siginPost.setEntity(reqEntity); 
		HttpResponse HtmlResp  = client.execute(siginPost); 
		if(HtmlResp.getEntity() != null){ 
			String jsonStr = EntityUtils.toString(HtmlResp.getEntity(), "UTF-8");
			JsonParser jp=new JsonParser(); 
	        JsonObject jo=jp.parse(jsonStr).getAsJsonObject();
	        String codevalue = jo.get("msg").getAsJsonObject().get("code").toString();
	        log.debug(jsonStr);
	        if("\"20\"".equals(codevalue)){
	        	response.head.rtnCode = "000000"; 
		    	response.head.rtnMsg = "登录成功"; 
	        }else if("\"21\"".equals(codevalue) || "\"22\"".equals(codevalue)){
	        	response.head.rtnCode = "900002"; 
		    	response.head.rtnMsg = "用户名或密码错误"; 
	        }else if("\"23\"".equals(codevalue)){
	        	response.head.rtnCode = "900001"; 
		    	response.head.rtnMsg = "验证码错误"; 
	        }else{
	        	response.head.rtnCode = "900006"; 
		    	response.head.rtnMsg = "账号尚未注册或登录过期"; 
	        } 
	    }else{
	    	response.head.rtnCode = "999999"; 
	    	response.head.rtnMsg = "系统返回异常"; 
	    }  
		return response.toJson();
    }  
	 
	
	@RequestMapping(params ="iw-cmd=quanyuanjiuzhixinxi") 
	@ResponseBody
    public String quanyuanjiuzhixinxi(@RequestParam(value="YM",required = false) String ym) throws UnsupportedOperationException, IOException{
		Response response = new Response();
		response.head.rtnCode = "000000"; 
		HttpClient client =  getClientSSL(); 
		HttpPost siginPost = new HttpPost("https://localhost/card/loadSeriousIllnessTreatment.do"); 
		siginPost.setHeader("User-Agent", agent);
		siginPost.setHeader("Host","localhost"); 
		siginPost.setHeader("Cookie",super.cookie); 
		siginPost.setHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8"); 
		siginPost.setHeader("X-Requested-With","XMLHttpRequest"); 
		if(StringUtils.isBlank(ym)){
			ym = "1";
		}
		
		List <NameValuePair> nvps = new ArrayList <NameValuePair>();
		nvps.add(new BasicNameValuePair("shengXzqh","150000000000"));
		nvps.add(new BasicNameValuePair("shiXzqh","150400000000")); 
		nvps.add(new BasicNameValuePair("pageFlag","page1"));
		nvps.add(new BasicNameValuePair("symbol","1"));
		nvps.add(new BasicNameValuePair("pageNumber",ym));
		nvps.add(new BasicNameValuePair("pageSize",pageSize));
	 
		//转码  封装成请求实体
		HttpEntity reqEntity = new UrlEncodedFormEntity(nvps,Consts.UTF_8); 
		siginPost.setEntity(reqEntity); 
		HttpResponse HtmlResp  = client.execute(siginPost); 
		if(HtmlResp.getEntity() != null){ 
			String jsonStr = EntityUtils.toString(HtmlResp.getEntity(), "UTF-8");
			log.debug(jsonStr);
			JsonParser jp=new JsonParser(); 
	        JsonObject jo=jp.parse(jsonStr).getAsJsonObject();
	        String codevalue = jo.get("msg").getAsJsonObject().get("code").toString();
	        if("\"00\"".equals(codevalue)){ 
	        	JsonArray data = jo.get("data").getAsJsonObject().get("rows").getAsJsonArray();
	 	        if(data == null || data.size() == 0){
	 	        	response.head.rtnCode = "900005"; 
	 				response.head.rtnMsg = "没有当前查询信息";
	 				return response.toJson();
	 	        }  
	 	        response.head.rtnCode = "000000"; 
				response.head.rtnMsg = "请求成功";
				response.body.size=pageSize;
				response.body.totalCount="-1";
			    response.body.sql = WJWTableUtils.quanyuanjiuzhixinxi(data); 
			    log.debug(response.body.sql);
				return response.toJson(); 
		    	
	        }else if("\"20\"".equals(codevalue)){
	        	response.head.rtnCode = "000000"; 
		    	response.head.rtnMsg = "登录成功"; 
	        }else if("\"21\"".equals(codevalue) || "\"22\"".equals(codevalue)){
	        	response.head.rtnCode = "900002"; 
		    	response.head.rtnMsg = "用户名或密码错误"; 
	        }else if("\"23\"".equals(codevalue)){
	        	response.head.rtnCode = "900001"; 
		    	response.head.rtnMsg = "验证码错误"; 
	        }else{
	        	response.head.rtnCode = "900006"; 
		    	response.head.rtnMsg = "账号尚未注册或登录过期"; 
	        } 
	    }else{
	    	response.head.rtnCode = "999999"; 
	    	response.head.rtnMsg = "系统返回异常"; 
	    }  
		return response.toJson();
    }  
	
}